/**
 * create by young (young2f@outlook.com) on 2020/12/4
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const moment = require('moment');
const table = 'Customer';
module.exports = class extends base {
  async findCustomerDetail(body) {
    const { ctx } = this;
    console.log('findCustomerDetail body', body);
    const { code, tenantCode, createdTs, division, accountName } = body;
    const result = [];
    let _receiptAmount = 0,
      salesAmount = 0,
      outboundAmount = 0,
      invoiceAmount = 0,
      _laborFee = 0,
      _publicFee = 0,
      payLaborFee = 0,
      payPublicFee = 0;

    const queryRece = division ? { tenantCode, _accountName: division, 'customerCode': code } : {
      tenantCode,
      'customerCode': code
    };
    if (createdTs) {
      queryRece['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (accountName) queryRece['accountName'] = { $regex: accountName };

    const list = await ctx.app.dbs.find('Receipt', queryRece);

    _.map(list, item => {
      const { receiptAmount } = item;
      item.createdTs = item.date;
      if (receiptAmount) {
        _receiptAmount += receiptAmount;
        result.push(item);
      }
    });

    const querySales = division ? { tenantCode, division, customerCode: code } : { tenantCode, customerCode: code };
    if (createdTs) {
      querySales['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const salesOrderList = await ctx.app.dbs.find('SalesOrder', querySales);

    _.map(salesOrderList, item => {
      const { amount, prods, publicFee } = item;
      salesAmount += amount;
      _publicFee += publicFee;
      _.map(prods, prod => {
        const { laborFee } = prod;
        _laborFee += laborFee;
      });

    });

    const queryInvoice = division ? {
      tenantCode,
      customerCode: code,
      division,
      'prods.invoicingDate': { $exists: true, $ne: '' }
    } : { tenantCode, customerCode: code, 'prods.invoicingDate': { $exists: true, $ne: '' } };
    if (createdTs) {
      queryInvoice['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const invoiceList = await ctx.app.dbs.find('SalesOrder', queryInvoice);

    _.map(invoiceList, item => {
      const { prods } = item;
      _.map(prods, prod => {
        const { count, price } = prod;
        invoiceAmount += count * price;
      });
    });

    /**
     * 出货
     */
    delete queryInvoice['prods.invoicingDate'];
    queryInvoice['outboundCount'] = { $gt: 0 };
    const outboundList = await ctx.app.dbs.find('OutboundLot', queryInvoice);
    _.map(outboundList, item => {
      const { outboundCount, price = 0 } = item;
      outboundAmount += outboundCount * price;
    });
    /**
     * 劳务和公关费用
     * @type {{tenantCode, _accountName, payCustomerCode}|{tenantCode, payCustomerCode}}
     */
    const queryReceipt = division ? { tenantCode, _accountName: division, 'payCustomerCode': code } : {
      tenantCode,
      'payCustomerCode': code
    };

    if (createdTs) {
      queryReceipt['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const receiptRes = await ctx.app.dbs.find('Receipt', queryReceipt);

    _.map(receiptRes, item => {
      const { payType, paymentAmount = 0 } = item;
      if (payType === '劳务') {
        payLaborFee += paymentAmount;
      }
      if (payType === '公关') {
        payPublicFee += paymentAmount;
      }
    });
    /**
     * 返回收入记录、回款、销售、开票、发货金额
     */

    return {
      status: 'ok',
      result: {
        list: result,
        salesOrderList,
        receiptAmount: _receiptAmount,
        publicFee: _publicFee,
        salesAmount,
        invoiceAmount,
        outboundAmount,
        laborFee: _laborFee,
        payLaborFee,
        payPublicFee
      }
    };
  }

  async findMany(body) {
    const { ctx } = this;
    console.log('find customer many', body);
    const { start, end, key, name, code, phone } = body;
    const _key = key ? key : 'createdTs';
    if (start && end) {
      body[_key] = {
        $gte: new Date(moment(start)
          .valueOf()),
        $lt: new Date(moment(end)
          .valueOf())
      };
    }
    delete body['start'];
    delete body['end'];
    const sort = {};
    sort[_key] = -1;
    if (name) body['name'] = { $regex: name };
    if (code) body['code'] = { $regex: code };
    if (phone) body['phone'] = { $regex: phone };
    const res = await ctx.app.dbs.aggregate(table, [
      { $match: { ...body } },
      { $sort: { ...sort } },
    ]);
    const result = [];
    _.map(res, item => {
      const { labels } = item;
      _.map(labels, it => {
        _.assign(item, it);
      });
      result.push(item);
    });
    return { status: 'ok', result };
  }

  async updateOne(body) {
    const { ctx } = this;
    const { tenantCode, code } = body;
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, body);
    return { status: 'ok', result };
    return 'ok';
  }

  async deleteOne(body) {
    const { ctx } = this;
    const { tenantCode, code } = body;
    const result = await ctx.app.dbs.deleteOne(table, { tenantCode, code }, body);
    return { status: 'ok', result };
    return 'ok';
  }
};
